<template>
  <Dialog v-model="dialogVisible" :appendToBody="true" title="选择公告" width="60%">
    <el-form :inline="true" :model="queryParams" class="-mb-15px" label-width="68px">
      <el-form-item label="公告标题" prop="title">
        <el-input v-model="queryParams.title" class="!w-240px" clearable placeholder="请输入公告标题" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="list" @row-click="handleRowClick">
      <el-table-column label="#" width="55">
        <template #default="{ row }">
          <el-radio :value="row.id" v-model="selectedNoticeId">&nbsp;</el-radio>
        </template>
      </el-table-column>
      <el-table-column label="公告标题" prop="title" min-width="200" />
      <el-table-column label="公告类型" prop="type" min-width="80" />
      <el-table-column label="创建时间" prop="createTime" min-width="120" />
    </el-table>
    <el-pagination
      v-model:current-page="queryParams.pageNo"
      v-model:page-size="queryParams.pageSize"
      :total="total"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmSelect">确定</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getNoticePage } from '@/api/system/notice'
const dialogVisible = ref(false)
const loading = ref(false)
const list = ref([])
const total = ref(0)
const selectedNoticeId = ref()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  title: ''
})
const open = () => {
  dialogVisible.value = true
  getList()
}
defineExpose({ open })
const getList = async () => {
  loading.value = true
  try {
    const data = await getNoticePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const resetQuery = () => {
  queryParams.title = ''
  handleQuery()
}
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}
const handleCurrentChange = (val) => {
  queryParams.pageNo = val
  getList()
}
const handleRowClick = (row) => {
  selectedNoticeId.value = row.id
}
const emit = defineEmits(['change'])
const confirmSelect = () => {
  const notice = list.value.find(item => item.id === selectedNoticeId.value)
  if (notice) {
    emit('change', notice)
    dialogVisible.value = false
  }
}
</script> 